#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // 屏幕名称输入框
    screenNameEdit = new QLineEdit("DisplayPort-0", this);
    mainLayout->addWidget(screenNameEdit);

    // 屏幕数量下拉框
    screenCountCombo = new QComboBox(this);
    screenCountCombo->addItems({"1", "4", "6", "9"});
    screenCountCombo->setCurrentText("9");
    mainLayout->addWidget(screenCountCombo);

    // 打开按钮
    openButton = new QPushButton("打开", this);
    connect(openButton, &QPushButton::clicked, this, &MainWindow::onOpenButtonClicked);
    mainLayout->addWidget(openButton);

    // 图片选择按钮
    selectImagesButton = new QPushButton("选择图片", this);
    connect(selectImagesButton, &QPushButton::clicked, this, &MainWindow::onSelectImagesButtonClicked);
    mainLayout->addWidget(selectImagesButton);

    // 图片预览区域
    previewWidget = new QWidget(this);
    previewLayout = new QVBoxLayout(previewWidget);
    mainLayout->addWidget(previewWidget);

    // 图片清空按钮
    clearImagesButton = new QPushButton("清空图片", this);
    connect(clearImagesButton, &QPushButton::clicked, this, &MainWindow::onClearImagesButtonClicked);
    mainLayout->addWidget(clearImagesButton);

    // 发送按钮
    sendButton = new QPushButton("发送", this);
    sendButton->setEnabled(false);
    connect(sendButton, &QPushButton::clicked, this, &MainWindow::onSendButtonClicked);
    mainLayout->addWidget(sendButton);
    // 添加状态提示标签
    statusLabel = new QLabel("等待操作...", this); 
    mainLayout->addWidget(statusLabel);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onOpenButtonClicked()
{
    QString screenName = screenNameEdit->text();
    QString screenCount = screenCountCombo->currentText();
    QString program = "../ScreenSplitAssist";
    QStringList arguments;
    qDebug() << "screenCount:" << screenCount << "screenName:" << screenName;
    arguments << QString("--targetDisplayScreenName=%1").arg(screenName);
    arguments << QString("--screenSplitCount=%2").arg(screenCount);

    QProcess::startDetached(program, arguments);
}

void MainWindow::onSelectImagesButtonClicked()
{
    QStringList filePaths = QFileDialog::getOpenFileNames(this, "选择图片", "", "Images (*.jpg *.png)");
    if (!filePaths.isEmpty()) {
        selectedImages = filePaths;

        // 清空之前的预览
        QLayoutItem *item;
        while ((item = previewLayout->takeAt(0)) != nullptr) {
            delete item->widget();
            delete item;
        }

        QHBoxLayout *currentRowLayout = nullptr;
        for (int i = 0; i < selectedImages.size(); ++i) {
            if (i % 3 == 0) {
                // 每三张图片开始一个新的水平布局
                currentRowLayout = new QHBoxLayout;
                previewLayout->addLayout(currentRowLayout);
            }

            QImage image(selectedImages[i]);
            QPixmap pixmap = QPixmap::fromImage(image);
            QLabel *label = new QLabel(this);
            // 修改图片显示大小为150x100px
            label->setPixmap(pixmap.scaled(150, 100, Qt::KeepAspectRatio)); 

            // 在预览图右上角显示序号
            QPainter painter(&pixmap);
            painter.setPen(Qt::red);
            painter.setFont(QFont("Arial", 12));
            painter.drawText(pixmap.width() - 20, 20, QString::number(i + 1));
            label->setPixmap(pixmap.scaled(150, 100, Qt::KeepAspectRatio));

            currentRowLayout->addWidget(label);
        }

        // 更新发送按钮状态
        sendButton->setEnabled(selectedImages.size() > 0);
    }
}

void MainWindow::onClearImagesButtonClicked()
{
    selectedImages.clear();
    QLayoutItem *item;
    while ((item = previewLayout->takeAt(0)) != nullptr) {
        delete item->widget();
        delete item;
    }
    sendButton->setEnabled(false);
}

void MainWindow::onSendButtonClicked()
{
    QJsonArray jsonArray;
    for (int i = 0; i < selectedImages.size(); ++i) {
        QJsonObject jsonObject;
        jsonObject["zoneIndex"] = i + 1;
        jsonObject["imageUri"] = selectedImages[i];
        jsonArray.append(jsonObject);
    }

    QJsonDocument jsonDoc(jsonArray);
    QByteArray jsonData = jsonDoc.toJson();

    QLocalSocket socket;
    socket.connectToServer("/tmp/com.zltongxue.screenSplitAssist");
    if (socket.waitForConnected()) {
        socket.write(jsonData);
        socket.waitForBytesWritten();
        socket.close();
        // 显示连接成功提示
        statusLabel->setText("UDS 连接成功，数据已发送"); 
    } else {
        // 显示连接失败提示
        statusLabel->setText("UDS 连接失败，请检查服务是否运行"); 
    }
}
